package models

import
(
	"github.com/astaxie/beego/orm"
	"fmt"
	"encoding/json"
	"time"
)

type GpsInfo struct {
	Id int64
	Data string
	Labelid string
	Company string
	Timestamp int64
	Datatimestr string
}

//接收到的查询字符串
type Message struct {
	Labelname string `json:"labelname"`
	Duratime  string    `json:"duratime"`
}


//新增一条GPS数据
func AddGps(gps_info *GpsInfo)(int64,error){
	db := orm.NewOrm()
	id,err := db.Insert(gps_info)
	fmt.Println("OK")
	return id,err
}

//查询ＧＰＳ数据
func ReadGps(historyDataChan chan []byte,message string){

	fmt.Println("get messge from front:",message);
	//string 转　json
	var mess Message
	if err := json.Unmarshal([]byte(message), &mess); err != nil {
		fmt.Println(err)
	}
	//else {
	//
	//	fmt.Println(mess.Labelname)
	//	fmt.Println(mess.Duratime[:19])
	//	fmt.Println(mess.Duratime[21:40])
	//}
	timeLayout := "2006-01-02 15:04:05"                             //转化所需模板
	loc, _ := time.LoadLocation("Local")                            //重要：获取时区
	theTime1, _ := time.ParseInLocation(timeLayout, mess.Duratime[:19], loc) //使用模板在对应时区转化为time.time类型
	theTime2, _ := time.ParseInLocation(timeLayout, mess.Duratime[21:40], loc) //使用模板在对应时区转化为time.time类型

	begintime := theTime1.Unix()                                            //转化为时间戳 类型是int64
	endtime := theTime2.Unix()

	//使用原生查询
	var gpsrows []GpsInfo
	o := orm.NewOrm()
	if _, err := o.Raw("SELECT * FROM gps_info WHERE labelid = ? and timestamp > ? and timestamp < ?", mess.Labelname,begintime,endtime).QueryRows(&gpsrows); err != nil{
		fmt.Println("err")
		return
	}
	//fmt.Println("n =",n)
	for _,gpsrow := range gpsrows{
		//fmt.Println("gpsrow:",gpsrow.Data)

		historyDataChan <- []byte(gpsrow.Data)
	}
}


//模拟实时获取ＧＰＳ数据
func ReadGpsontime(gps_info *[]GpsInfo){
	qb, _:=orm.NewQueryBuilder("mysql")
	db := orm.NewOrm()

	qb.Select("data").From("gps_info")
	sql := qb.String()
	db.Raw(sql).QueryRows(gps_info)
}